package com.imnc.eatmap.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.imnc.eatmap.BaseApplication;
import com.imnc.eatmap.R;
import com.imnc.eatmap.model.PoiInfoParcelable;
import com.imnc.eatmap.ui.base.BaseSlidingActivity;
import com.imnc.eatmap.view.EatMapPoiOverlay;

/**
 * 主界面
 * 
 * @author acer
 * 
 */
public class MainActivity extends BaseSlidingActivity implements
		OnClickListener {
	public static final String MAP_ALL_POI_RESULT = "MAP_ALL_POI_RESULT";
	public static final int REQUEST_ROUTE_PLANNING = 1001;

	private String title = "美食";
	private static MainActivity mInstance = null;
	private static final float DEFINE_ZOOM = 14;

	private MapView mMapView = null;
	private MapController mMapController = null;
	private BaseApplication mApplication = null;

	public LocationClient mLocationClient = null;
	public BDLocationListener mLocationListener = null;

	private MyLocationOverlay mLocationOverlay = null;
	private LocationData locData = null;

	private Button mLocationButton = null;

	private MKSearch mSearch = null;
	private MKSearchListener mSearchListener = null;

	private ArrayList<MKPoiInfo> mSearchResultInfo = null;

	private RouteOverlay routeOverlay = null;

	public MainActivity() {
		super(R.string.about);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mInstance = this;

		setSlidingActionBarEnabled(true);
		setContentView(R.layout.activity_main);

		setTitle(title);

		mApplication = BaseApplication.getInstance();

		if (mApplication.getmBMapManager() == null) {
			mApplication.setmBMapManager(new BMapManager(
					getApplicationContext()));
			mApplication.getmBMapManager().init(
					new BaseApplication.EatMapMKGeneralListener());
		}

		initViews();

		initEvents();

	}

	protected void initViews() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		mLocationListener = new MyLocationListener();
		mLocationClient = new LocationClient(getApplicationContext());
		mLocationButton = (Button) findViewById(R.id.btn_location);
		mMapController = mMapView.getController();
		locData = new LocationData();
		// 定位图层初始化
		mLocationOverlay = new MyLocationOverlay(mMapView);
		mSearchListener = new EatMKSearchListener();
		mSearch = new MKSearch();

		routeOverlay = new RouteOverlay(MainActivity.this, mMapView); // 此处仅展示一个方案作为示例

	}

	protected void initEvents() {
		mMapView.setBuiltInZoomControls(true);
		mLocationButton.setOnClickListener(this);

		mMapController.enableClick(true);
		mMapController.setZoom(DEFINE_ZOOM);

		mSearch.init(mApplication.getmBMapManager(), mSearchListener);
		// 声明LocationClient类
		mLocationClient.registerLocationListener(mLocationListener);

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);// 禁止启用缓存定位
		option.setPoiNumber(5); // 最多返回POI个数
		option.setPoiDistance(1000); // poi查询距离
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		mLocationClient.setLocOption(option);
		mLocationClient.start();

		// 设置定位数据
		mLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(mLocationOverlay);
		mLocationOverlay.enableCompass();
		// 修改定位数据后刷新图层生效
		mMapView.refresh();

	}

	/**
	 * 定位Listener
	 * 
	 * @author acer
	 * 
	 */
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation poiLocation) {
			if (poiLocation == null)
				return;
			locData.latitude = poiLocation.getLatitude();
			locData.longitude = poiLocation.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = poiLocation.getRadius();
			// 此处可以设置 locData的方向信息, 如果定位 SDK 未返回方向信息，用户可以自己实现罗盘功能添加方向信息。
			locData.direction = poiLocation.getDerect();
			// 更新定位数据
			mLocationOverlay.setData(locData);
			// 更新图层数据执行刷新后生效
			mMapView.refresh();
			// 是手动触发请求或首次定位时，移动到定位点
			Log.d("LocationOverlay", "receive location, animate to it");
			mMapController.animateTo(new GeoPoint(
					(int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6)));
			mLocationOverlay
					.setLocationMode(com.baidu.mapapi.map.MyLocationOverlay.LocationMode.NORMAL);

			switchMap(title);
		}

		public void onReceivePoi(BDLocation poiLocation) {
			// 将在下个版本中去除poi功能
			if (poiLocation == null) {
				return;
			}

		}
	}

	/**
	 * 搜索Listener
	 * 
	 * @author acer
	 * 
	 */
	private class EatMKSearchListener implements MKSearchListener {
		// 在此处理详情页结果
		@Override
		public void onGetPoiDetailSearchResult(int type, int error) {
			if (error != 0) {
				// showShortToast("抱歉，未找到结果");
			} else {

			}
		}

		/**
		 * 在此处理poi搜索结果
		 */
		public void onGetPoiResult(MKPoiResult res, int type, int error) {
			// 错误号可参考MKEvent中的定义
			if (error != 0 || res == null) {
				// showShortToast("抱歉，未找到结果");
				return;
			}
			// 将地图移动到第一个POI中心点
			if (res.getCurrentNumPois() > 0) {
				// 将poi结果显示到地图上
				EatMapPoiOverlay poiOverlay = new EatMapPoiOverlay(
						MainActivity.this, mMapView, mSearch);
				poiOverlay.setData(res.getAllPoi());
				mMapView.getOverlays().add(poiOverlay);
				mMapView.refresh();
				// 当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空

				mSearchResultInfo = res.getAllPoi();
				for (MKPoiInfo info : res.getAllPoi()) {
					if (info.pt != null) {
						mMapView.getController().animateTo(info.pt);
						break;
					}
				}
			} else if (res.getCityListNum() > 0) {
				// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
				String strInfo = "在";
				for (int i = 0; i < res.getCityListNum(); i++) {
					strInfo += res.getCityListInfo(i).city;
					strInfo += ",";
				}
				strInfo += "找到结果";
				showShortToast(strInfo);
			}
		}

		public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {

			routeOverlay.setData(res.getPlan(0).getRoute(0));
			mMapView.getOverlays().remove(routeOverlay);
			mMapView.getOverlays().add(routeOverlay);
			mMapView.refresh();
		}

		public void onGetTransitRouteResult(MKTransitRouteResult res, int error) {

			showAlertDialog(res.toString(), error + "");
		}

		public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) {
		}

		public void onGetAddrResult(MKAddrInfo res, int error) {
		}

		public void onGetBusDetailResult(MKBusLineResult result, int iError) {
		}

		/**
		 * 更新建议列表
		 */
		@Override
		public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			if (res == null || res.getAllSuggestions() == null) {
				return;
			}
		}

		@Override
		public void onGetShareUrlResult(MKShareUrlResult result, int type,
				int error) {

		}
	}

	@Override
	protected void onDestroy() {
		mSearch.destory();
		mMapView.destroy();
		mLocationClient.stop();

		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_location:
			mLocationClient.requestLocation();
			break;

		default:
			break;
		}
	}

	public static MainActivity getInstance() {
		return mInstance;
	}

	public void switchMap(String content) {

		title = content;
		mSearch.poiSearchNearBy(content,
				new GeoPoint((int) (locData.latitude * 1e6),
						(int) (locData.longitude * 1e6)), 2000);
		getSlidingMenu().showContent();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.detail:

			if (mSearchResultInfo == null || mSearchResultInfo.size() == 0) {
				showShortToast("附近沒有你想要的");
				break;
			}

			Intent intent = new Intent();
			intent.setClass(this, SearchResultActivity.class);
			Bundle bundle = new Bundle();
			ArrayList<PoiInfoParcelable> allPoiInfo = new ArrayList<PoiInfoParcelable>();
			for (MKPoiInfo poiInfo : mSearchResultInfo) {
				allPoiInfo.add(new PoiInfoParcelable(poiInfo));
			}
			bundle.putParcelableArrayList(MAP_ALL_POI_RESULT, allPoiInfo);
			intent.putExtras(bundle);
			startActivity(intent);

			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		defaultFinish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case MainActivity.REQUEST_ROUTE_PLANNING:

			if (data != null) {
				PoiInfoParcelable poiInfoParcelable = data
						.getParcelableExtra("poiInfoParcelable");

				MKPlanNode start = new MKPlanNode();
				start.pt = new GeoPoint((int) (locData.latitude * 1e6),
						(int) (locData.longitude * 1e6));

				MKPlanNode end = new MKPlanNode();

				end.pt = poiInfoParcelable.pt;
				mSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
				mSearch.transitSearch(null, start, end);
				mSearch.drivingSearch(null, start, null, end);
			}

			break;

		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}
